/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package util;

import dao.DBManager;
import javax.microedition.lcdui.Image;

/**
 *
 * @author kien.tran
 */
public class ImageUtils {

    public static Image scaleImage(Image original, int newWidth, int newHeight) {
        int[] rawInput = new int[original.getHeight() * original.getWidth()];
        original.getRGB(rawInput, 0, original.getWidth(), 0, 0, original.getWidth(), original.getHeight());

        int[] rawOutput = new int[newWidth * newHeight];

        // YD compensates for the x loop by subtracting the width back out
        int YD = (original.getHeight() / newHeight) * original.getWidth() - original.getWidth();
        int YR = original.getHeight() % newHeight;
        int XD = original.getWidth() / newWidth;
        int XR = original.getWidth() % newWidth;
        int outOffset = 0;
        int inOffset = 0;

        for (int y = newHeight, YE = 0; y > 0; y--) {
            for (int x = newWidth, XE = 0; x > 0; x--) {
                rawOutput[outOffset++] = rawInput[inOffset];
                inOffset += XD;
                XE += XR;
                if (XE >= newWidth) {
                    XE -= newWidth;
                    inOffset++;
                }
            }
            inOffset += YD;
            YE += YR;
            if (YE >= newHeight) {
                YE -= newHeight;
                inOffset += original.getWidth();
            }
        }
        return Image.createRGBImage(rawOutput, newWidth, newHeight, false);
    }

    public static boolean isExist(Image[] images) {
        if (images != null) {
            for (int i = 0; i < images.length; i++) {
                if (null == images[i]) {
                    return false;
                }
            }
        } else {
            return false;
        }

        return true;
    }

    public static Image getImage(Image[] images) {
        if (images != null) {
            for (int i = 0; i < images.length; i++) {
                if (images[i] != null) {
                    return images[i];
                }
            }
        }
        return null;
    }

    public static Image restoreRmsImage(String widthName, String heightName, String rmsName) {
        // advApp
        Image img = null;
//        String sw = DBManager.getSetting(DBManager.DB_CONFIG, widthName);
//        String sh = DBManager.getSetting(DBManager.DB_CONFIG, heightName);
//        if (sw != null && sw.trim().length() > 0 && sh != null && sh.trim().length() > 0) {
//            int iw = 0, ih = 0;
//            iw = Integer.parseInt(sw);
//            ih = Integer.parseInt(sh);
//            img = DBManager.loadImage(rmsName, iw, ih);
//        }

        return img;
    }
}
